package webservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import util.GoogleMapsAdressFetch;

/**
 * Trabalho PD - 2014/2015
 *
 * @author a21210380 a21210392
 */
@Path("/GoogleGeoService")
public class GoogleGeoService {

    @GET
    @Path("/getPossibleLocations/lat={lat}&lng={lng}")
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.APPLICATION_JSON)
    public String getPossibleLocations(@PathParam("lat") double lat, @PathParam("lng") double lng) {
        try {
            List<GoogleMapsAdressFetch.Address> adress = new ArrayList<>();
            String res = GoogleMapsAdressFetch.useGoogleGeocodingAPI(lat, lng, adress);
            if (res.equals(GoogleMapsAdressFetch.STATUS_OK)) {
                JsonArrayBuilder createArrayBuilder = Json.createArrayBuilder();
                for (GoogleMapsAdressFetch.Address ad : adress) {
                    JsonObjectBuilder add = Json.createObjectBuilder()
                            .add(GoogleMapsAdressFetch.KEY_NEIGHBORHOOD, ad.getNeighborhood())
                            .add(GoogleMapsAdressFetch.KEY_ROUTE, ad.getRoute())
                            .add(GoogleMapsAdressFetch.KEY_POSTAL_CODE, ad.getPostalCode())
                            .add(GoogleMapsAdressFetch.KEY_COUNTRY, ad.getCountry())
                            .add(GoogleMapsAdressFetch.KEY_FREGUESIA, ad.getFreguesia())
                            .add(GoogleMapsAdressFetch.KEY_CONCELHO, ad.getConselho())
                            .add(GoogleMapsAdressFetch.KEY_DISTRITO, ad.getDistrito());
                    createArrayBuilder.add(add.build());
                }
                
                return Json.createObjectBuilder().add("address", createArrayBuilder.build()).build().toString();
            } else {
            }
        } catch (IOException ex) {
            return ex.toString();
        }
        return "[\"sucess\":true]";
    }
}
